package com.jnu.assistant.controller;

import com.jnu.assistant.pojo.Result;
import com.jnu.assistant.pojo.Code2SessionResponse;
import com.jnu.assistant.pojo.UserOpenId;
import com.jnu.assistant.service.LoginService;
import com.jnu.assistant.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/login/{code}")
    public Result login(@PathVariable String code) {
        log.info("进入登录接口，code: {}", code); // 添加日志
        try {
            Code2SessionResponse sessionResponse = loginService.code2Session(code);
            UserOpenId userOpenId=new UserOpenId();
            userOpenId.setOpenId(sessionResponse.getOpenid());
            userOpenId.setUserId(loginService.getUserId(userOpenId.getOpenId()));
            log.info("userId的值为："+userOpenId.getUserId());
            if(userOpenId.getUserId()==null){
                log.info("userId的值为空");
                loginService.insertId(userOpenId);
            }
            String sessionKey = sessionResponse.getSession_key();
            String token = JwtUtils.generateJwt(userOpenId.getUserId());
            log.info(token + "  令牌" + sessionKey);
            return Result.success(token);
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("登录失败");
        }
    }
}
